//
//  UserAccount.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/4.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    
//   设置模型的属性
    var access_token:String?
    var expires_in: NSTimeInterval = 0 {
        didSet{
//   计算过期的日期
            expiresDate  = NSDate(timeIntervalSinceNow:expires_in)
        }
    }
    
/// 过期的日期
    var expiresDate: NSDate?
/// 当前授权用户的UID
    var uid: String?
    
/// 友好显示名称
    var name:String?
/// 用户头像地址(大图)180*180像素
    var avatar_large:String?
    
    init(dict:[String:AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description:String{
        let keys = ["access_token","expires_in", "expiresDate", "uid", "name", "avatar_large"]
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    
/// xcode7.0 bata5 之后,拼接路径改为NSString函数
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
/// 归档
    func saveUserAccount(){
        print("plist保存在沙盒中的路径"+UserAccount.accountPath)
    // 键值归档
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
/// 解档(加载用户的信息)
/// - returns: 如果用户没有登录,返回nil
    class func loadUserAccount() ->UserAccount? {
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        // 解档加载的时候,判断token的有效期
        if let date = account?.expiresDate{
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
    
// MARK:--NSCoding
// 归档,将当前对象保存到磁盘之前,转换为二进制数据(序列化)
    func encodeWithCoder(aCoder:NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
// 解档,将二进制数据从磁盘加载,转换成自定义的对象时调用(反序列化对象)
    required init?(coder aDecoder:NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}
